//账单
'use strict'
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ListView,
  Image,
  Alert,
  ActivityIndicator,
} from 'react-native';
import * as defaultStyles from '../constants/DefaultStyles';
import Menu from '../components/Menu';
import { Actions } from 'react-native-router-flux';
import NavBar from '../components/NavigatorBar';
import { requestXML } from '../utils/RequestUtils';
import { json2xml_str } from '../utils/XmlUtils';
import Spinner from 'react-native-loading-spinner-overlay'
import {stringFormatOfTime} from '../utils/DateAndTime';
import {tradeState} from '../constants/TradeState';
import PullToRefreshListView from 'react-native-smart-pull-to-refresh-listview';

function  isWechat(string:String) {
  let type = string.substring(0, 4);
  return type === 'svcW';
}

export default class BillContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      dataSource: [],
      ds: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
    }
  }
  componentDidMount() {
    this._pullToRefreshListView.beginRefresh();
    // this._update(false);
  }
  _update(isLoading: Boolean) {
    this.setState({isLoading: isLoading});
    console.log(this.state.code);
    let xml = json2xml_str(JSON.stringify({
      Request: {
        Head: {
          trace_no: '6',
          terminalno: '8',
          acceptidcode: merid,
          tanstype: '10002',
          operateno: '3'
        },
        Body: {
          SIGN: '122',
          trancode: this.state.code,
          trandate: this.state.date,
          transtat: this.state.stat
        }}
    }));
    let respcd = '-1';
    const promise = requestXML('http://192.168.4.13:8084/icmp-ums/dhc/sys/mobile.do', xml, 15000);
    promise.then((object) => {
      console.log(object);
      let result;
      this._pullToRefreshListView.endRefresh();
      try{
        let total = object.Response.Body.total;
        if (total === '0') {
          this.setState({dataSource: [], isLoading: false});
          return;
        }
        else if (total === '1') {
          result = new Array(object.Response.Body.trans.batch);
        }
        else {
          result = object.Response.Body.trans.batch;
        }
        this.setState({dataSource: result, isLoading: false});
      }
      catch (e) {
        console.log(e);
      }
    }, (reject) => {
      this._pullToRefreshListView.endRefresh();
      Alert.alert('提示', '请求超时，请检查网络连接', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
    });
  }
  _renderRow(rowData) {
    return (
      <View style={styles.listCell}>
        <View style={styles.whiteContainer} />
        <TouchableOpacity style={{flex: 1, flexDirection: 'row', borderBottomColor: "#F5F5F5", borderBottomWidth: 0.5}}
                          onPress={() => Actions.billDetail({
                          receiptMoney: '￥' + rowData['amt'],
                          paymentType: rowData['trancode'].substring(0, 4),
                          time: stringFormatOfTime(rowData['trandate'], 'date', '/')+ ' ' +stringFormatOfTime(rowData['trantime'], 'time', ':'),
                          transtat: rowData['transtat'],
                          transid: rowData['transid'],
                          outtradeno: rowData['outtradeno'],
                          back: () => {
                            {/*this.setState({isLoading: true});*/}
                            this._pullToRefreshListView.beginRefresh()
                            {/*timer.setTimeout(*/}
                            {/*this, 'refresh',() => this._pullToRefreshListView.beginRefresh(), 200)*/}
                          },
                        })}>
          <Image source={isWechat(rowData['trancode']) ? require('../imgs/wechat.png') : require('../imgs/alipay.png')}
                 style={{width: 30, height: 30, marginTop: 15, marginBottom: 15}}/>
          <View style={styles.cellLeftPart}>
            <Text style={{fontSize: 13, marginBottom: 5, fontWeight: "bold"}}>{isWechat(rowData['trancode']) ? '微信收款支付' : '支付宝支付'}</Text>
            <Text style={{fontSize: 11, marginTop: 5}}>{stringFormatOfTime(rowData['trantime'], 'time', ':')}</Text>
          </View>
          <View style={styles.cellRightPart}>
            <Text style={{textAlign: 'right',fontSize: 13, marginBottom: 5, fontWeight: "bold",
          color: rowData['transtat'] === 'ST00' ? 'black' : 'gray' ,marginRight: 15, width: 200}}>{'￥' + rowData['amt']}</Text>
            <Text style={{fontSize: 11, marginTop: 5, marginRight: 15,
          color: rowData['transtat'] === 'ST00' ? 'green' : 'gray'}}>{tradeState(rowData['transtat'])}</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
  render () {
    return (
      <View style={styles.container}>
        <Spinner visible={this.state.isLoading}
                 textStyle={{color: 'white'}}  overlayColor={'rgba(0, 0, 0, 0.7)'}/>
        {/*<NavBar leftImage={'search'} title="账单" rightText="报表" leftClick={() => Actions.search()}*/}
                {/*rightClick={() => Actions.form()} navBarColor={defaultStyles.LIGHTBLUE}*/}
                {/*leftImageSize={20} />*/}
        <NavBar title="账单" navBarColor={defaultStyles.LIGHTBLUE}/>
        <View style={{position: 'absolute', left: 0, right: 0, top: 64, bottom: 0,
          justifyContent: 'center', alignItems: 'center'}}>
          <Text style={{fontSize: 20}}>暂无</Text>
        </View>
        <Menu style={styles.menuContainer} onChange={(date, code, stat) => {
          this.state.code = code;
          this.state.date = date;
          this.state.stat = stat;
          this.setState({isLoding: true});
          this._pullToRefreshListView.beginRefresh();
          }
        } code={this.state.code} stat={this.state.date}/>
        <View style={styles.contentContainer}>
          <PullToRefreshListView
            ref={ (component) => this._pullToRefreshListView = component }
            viewType={PullToRefreshListView.constants.viewType.listView}
            dataSource={this.state.ds.cloneWithRows(this.state.dataSource)}
            renderRow={this._renderRow.bind(this)}
            style={styles.listContainer}
            enableEmptySections={true}
            renderHeader={this._renderHeader}
            contentContainerStyle={{backgroundColor: this.state.dataSource.length === 0 ? 'rgba(0,0,0,0)' : 'white', borderWidth: 0}}
            //renderFooter={this._renderFooter}
            //renderSeparator={(sectionID, rowID) => <View style={styles.separator} />}
            onRefresh={() => this._update()}
            pullDownDistance={35}
            pullDownStayDistance={50}
            enabledPullUp={false}
          />
        </View>
      </View>
    );
  }
  _renderHeader = (viewState) => {
    let {pullState, pullDistancePercent} = viewState
    let {refresh_none, refresh_idle, will_refresh, refreshing,} = PullToRefreshListView.constants.viewState
    pullDistancePercent = Math.round(pullDistancePercent * 100)
    switch(pullState) {
      case refresh_none:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.WHITEOFBACKGROUND,}}>
            <Text></Text>
          </View>
        )
      case refresh_idle:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.WHITEOFBACKGROUND,}}>
            <Text>下拉刷新数据{pullDistancePercent}%</Text>
          </View>
        )
      case will_refresh:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.WHITEOFBACKGROUND,}}>
            <Text>松手刷新数据{pullDistancePercent > 100 ? 100 : pullDistancePercent}%</Text>
          </View>
        )
      case refreshing:
        return (
          <View style={{flexDirection: 'row', height: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.WHITEOFBACKGROUND,}}>
            {this._renderActivityIndicator()}<Text>数据请求中</Text>
          </View>
        )
    }
  }

  _renderFooter = (viewState) => {
    let {pullState, pullDistancePercent} = viewState
    let {load_more_none, load_more_idle, will_load_more, loading_more, loaded_all, } = PullToRefreshListView.constants.viewState
    pullDistancePercent = Math.round(pullDistancePercent * 100)
    switch(pullState) {
      case load_more_none:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.LIGHTBLUE,}}>
            <Text>pull up to load more</Text>
          </View>
        )
      case load_more_idle:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.LIGHTBLUE,}}>
            <Text>pull up to load more{pullDistancePercent}%</Text>
          </View>
        )
      case will_load_more:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.LIGHTBLUE,}}>
            <Text>release to load more{pullDistancePercent > 100 ? 100 : pullDistancePercent}%</Text>
          </View>
        )
      case loading_more:
        return (
          <View style={{flexDirection: 'row', height: 35, justifyContent: 'center', alignItems: 'center', backgroundColor: defaultStyles.LIGHTBLUE,}}>
            {this._renderActivityIndicator()}<Text>loading</Text>
          </View>
        )
      case loaded_all:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center', backgroundColor: 'pink',}}>
            <Text>no more</Text>
          </View>
        )
    }
  }

  _renderActivityIndicator() {
    return ActivityIndicator ? (
        <ActivityIndicator
          style={{marginRight: 10,}}
          animating={true}
          color={'gray'}
          size={'small'}/>
      ) : Platform.OS == 'android' ?
        (
          <ProgressBarAndroid
            style={{marginRight: 10,}}
            color={'gray'}
            styleAttr={'Small'}/>

        ) :  (
          <ActivityIndicatorIOS
            style={{marginRight: 10,}}
            animating={true}
            color={'gray'}
            size={'small'}/>
        )
  }
}



const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: defaultStyles.WHITEOFBACKGROUND,
  },
  menuContainer: {
    flex: 1,
    backgroundColor: defaultStyles.WHITEOFBACKGROUND,
    borderBottomWidth: 1.2,
    borderBottomColor: '#F0F0F0'
  },
  contentContainer: {
    flex: 11,
    flexDirection: 'row',
  },
  //列表左侧空白
  whiteContainer: {
    width: 20,
    borderBottomWidth: 0.5,
    borderBottomColor: 'white',
  },
  listContainer: {
    flex: 1,
  },
  //cell容器
  listCell: {
    height: 60,
    flexDirection: 'row',
    backgroundColor: 'white'
  },
  //cell内部左半边容器（付款渠道，时间）
  cellLeftPart: {
    flex: 1,
    paddingLeft: 10,
    flexDirection: 'column',
    justifyContent: 'center',
  },
  //cell内部右半容器（金额，支付状态）
  cellRightPart: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'flex-end',

  }
});
